# -*- coding: utf-8 -*-
# article_info.py
# Created by Hardy on 26th, Jan
# Copyright 2017 杭州网川教育有限公司. All rights reserved.


from querier.esquerier import ElasticSearchQuerier
import psycopg2


class DramaQuerier(ElasticSearchQuerier):

    def __init__(self, article_search, config):
        super(DramaQuerier, self).__init__(None, None, None)
        self.article_search = article_search
        self.host = config['host']
        self.port = config['port']
        self.user = config['user']
        self.password = config['password']
        self.db = config['database']
        # self.table = config['table']

    def search(self, args):
        arg_dict = args.get('arg_dict')
        arg_dict = {} if not arg_dict else arg_dict

        offset = arg_dict.get('offset', 0)
        limit = arg_dict.get('limit', 10)
        is_get_article = arg_dict.get('is_get_article', True)

        conn, cur = None, None

        res = []

        try:
            conn = psycopg2.connect(database=self.db, user=self.user, password=self.password,
                                    host=self.host, port=self.port)

            cur = conn.cursor()

            sql = """select 
                     name, 
                     img,
                     status,
                     play_num,
                     score,
                     update_rule,
                     director,
                     type,
                     language,
                     intro,
                     year,
                     actors,
                     area
                     from iqiyi_tv_series where score is not null and year is not null 
                     order by year desc, score desc limit %s offset %s"""
            cur.execute(sql, (limit, offset))
            for d in cur.fetchall():
                print(d)
                res.append({
                    'title': d[0],
                    'img': d[1],
                    'status': d[2],
                    'play_num': d[3],
                    'score': d[4],
                    'update_rule': d[5],
                    'director': d[6],
                    'type': d[7],
                    'language': d[8],
                    'intro': d[9],
                    'year': d[10],
                    'actors': d[11],
                    'area': d[12]

                })

        except Exception as e:
            print(str(e))
        finally:
            if conn:
                conn.close()

        result = []
        for d in res:
            title = d['title']
            if is_get_article:
                out = self.article_search.search({'from': 0, 'size': 10, 'order_by': 'read_num',
                                                  'filters': {'title_filter_keywords': [[title]]}})
            else:
                out = {}

            result.append({
                'title': title,
                'info': d,
                'articles': out.get('articles', [])
            })

        return {
            "result": result
        }

    def _build_query(self, args): pass

    def _build_result(self, result, param): pass
